<template>
  <header class="bg-white border-b border-gray-100 fixed top-0 left-0 right-0 z-50">
    <div class="flex items-center justify-between h-12 px-6">
      <!-- 左侧Logo和导航 -->
      <div class="flex items-center flex-1">
        <!-- Logo -->
        <router-link
          to="/"
          class="flex items-center mr-8 hover:opacity-80 transition-opacity no-underline"
        >
          <span
            class="text-lg font-semibold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent whitespace-nowrap"
          >
            AI管理平台
          </span>
        </router-link>

        <!-- 主导航 - 居中显示 -->
        <div class="flex-1 flex justify-center">
          <a-menu mode="horizontal" class="border-0">
            <a-menu-item key="explore">
              <template #icon><BaseIcon name="icon-compass" /></template>
              <span class="menu-label">探索</span>
            </a-menu-item>
            <a-menu-item key="workspace">
              <template #icon><BaseIcon name="icon-apps" /></template>
              <span class="menu-label">工作室</span>
            </a-menu-item>
            <a-menu-item key="knowledge">
              <template #icon><BaseIcon name="icon-book" /></template>
              <span class="menu-label">知识库</span>
            </a-menu-item>
            <a-menu-item key="tools">
              <template #icon><BaseIcon name="icon-tool" /></template>
              <span class="menu-label">工具</span>
            </a-menu-item>
          </a-menu>
        </div>
      </div>

      <!-- 右侧功能区 -->
      <div class="flex items-center space-x-2">
        <!-- 搜索框 -->
        <a-input-search placeholder="搜索..." size="mini" class="w-44">
          <template #prefix>
            <BaseIcon name="icon-search" />
          </template>
        </a-input-search>

        <!-- 通知中心 -->
        <a-dropdown trigger="click">
          <a-badge :count="notifications.length">
            <div
              class="flex items-center justify-center h-7 w-7 rounded-lg bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors text-gray-500 hover:text-gray-700"
            >
              <BaseIcon name="icon-notification" />
            </div>
          </a-badge>
          <template #content>
            <div class="w-72">
              <div class="px-3 py-2 border-b border-gray-100">
                <div class="flex items-center justify-between">
                  <span class="font-medium text-sm">通知中心</span>
                  <a-link>全部已读</a-link>
                </div>
              </div>
              <div class="max-h-72 overflow-y-auto">
                <div
                  v-for="notice in notifications"
                  :key="notice.id"
                  class="px-3 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100"
                >
                  <div class="flex justify-between">
                    <span class="font-medium text-sm">{{ notice.title }}</span>
                    <span class="text-xs text-gray-400">{{ notice.time }}</span>
                  </div>
                  <p class="text-xs text-gray-500 mt-1">{{ notice.content }}</p>
                </div>
              </div>
            </div>
          </template>
        </a-dropdown>

        <!-- 全屏按钮 -->
        <div
          class="flex items-center justify-center h-7 w-7 rounded-lg bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors text-gray-500 hover:text-gray-700"
        >
          <BaseIcon name="icon-fullscreen-exit" />
        </div>

        <!-- 用户信息 -->
        <a-dropdown trigger="click" @visible-change="handleVisibleChange">
          <div class="flex items-center cursor-pointer">
            <a-avatar :size="28" :image-url="userInfo.avatar" />
            <!-- <span class="ml-2 text-sm">{{ userInfo.name }}</span> -->
            <BaseIcon
              name="icon-down"
              :class="['ml-1 transition-transform', userMenuVisible ? 'rotate-180' : '']"
              :size="14"
            />
          </div>
          <template #content>
            <div class="w-56">
              <!-- 用户信息卡片 -->
              <div class="px-4 py-3 border-b border-gray-100">
                <div class="flex items-center">
                  <a-avatar :size="36" :image-url="userInfo.avatar" />
                  <div class="ml-3">
                    <div class="font-medium">{{ userInfo.name }}</div>
                    <div class="text-xs text-gray-500">{{ userInfo.role }}</div>
                  </div>
                </div>
              </div>

              <!-- 根据登录状态显示不同的菜单选项 -->
              <template v-if="authStore.isLoggedIn">
                <a-doption @click="handleShowProfile">
                  <template #icon><BaseIcon name="icon-user" /></template>
                  个人信息
                </a-doption>
                <a-doption @click="handleSettings">
                  <template #icon><BaseIcon name="icon-settings" /></template>
                  设置
                </a-doption>
                <a-divider margin="0" />
                <a-doption @click="handleLogout" :disabled="loading">
                  <template #icon>
                    <BaseIcon name="icon-export" :style="{ opacity: loading ? 0.5 : 1 }" />
                  </template>
                  {{ loading ? '退出中...' : '退出登录' }}
                </a-doption>
              </template>
              <template v-else>
                <router-link to="/login">
                  <a-doption>
                    <template #icon><BaseIcon name="icon-export" /></template>
                    登录
                  </a-doption>
                </router-link>
              </template>
            </div>
          </template>
        </a-dropdown>
      </div>
    </div>
  </header>

  <!-- 占位符 -->
  <div class="h-12"></div>

  <!-- 添加 loading 组件 -->
  <LoadingSpinner :visible="loading" :text="loadingText" />

  <!-- 个人信息弹窗 -->
  <a-modal v-model:visible="showProfileModal" title="个人信息" :footer="false" :width="500">
    <div class="p-6">
      <!-- 头像区域 -->
      <div class="flex justify-center mb-8">
        <div class="relative">
          <a-avatar :size="88" :image-url="userInfo.avatar" />
          <div
            class="absolute -bottom-1 left-1/2 -translate-x-1/2 px-3 py-1 bg-blue-500 rounded-full text-white text-xs max-w-[120px]"
          >
            <span class="block truncate">{{ userInfo.name }}</span>
          </div>
        </div>
      </div>

      <!-- 基本信息区域 -->
      <div class="grid grid-cols-2 gap-6 mb-6">
        <div class="info-item">
          <div class="info-label">账号</div>
          <div class="info-value">{{ userInfo.account || '-' }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">真实姓名</div>
          <div class="info-value">{{ userInfo.realName || '-' }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">邮箱</div>
          <div class="info-value">{{ userInfo.email || '-' }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">手机号</div>
          <div class="info-value">{{ userInfo.phone || '-' }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">性别</div>
          <div class="info-value">
            {{ userInfo.sex === 1 ? '男' : userInfo.sex === 2 ? '女' : '-' }}
          </div>
        </div>
        <div class="info-item">
          <div class="info-label">生日</div>
          <div class="info-value">{{ userInfo.birthday || '-' }}</div>
        </div>
      </div>

      <!-- 状态信息区域 -->
      <div class="flex gap-6 mb-8">
        <div
          class="flex-1 status-card"
          :class="userInfo.status === 1 ? 'bg-green-50' : 'bg-red-50'"
        >
          <BaseIcon
            name="icon-check-circle"
            class="text-xl"
            :class="userInfo.status === 1 ? 'text-green-500' : 'text-red-500'"
          />
          <div class="mt-2">账号状态</div>
          <div
            class="text-lg font-medium"
            :class="userInfo.status === 1 ? 'text-green-500' : 'text-red-500'"
          >
            {{ userInfo.status === 1 ? '正常' : '停用' }}
          </div>
        </div>
        <div class="flex-1 status-card bg-blue-50">
          <BaseIcon name="icon-user" class="text-xl text-blue-500" />
          <div class="mt-2">用户角色</div>
          <div class="text-lg font-medium text-blue-500">
            {{ userInfo.role || userInfo.roles?.[0] || '普通用户' }}
          </div>
        </div>
      </div>

      <!-- 修改操作按钮区域的样式和位置 -->
      <div class="border-t border-gray-100 mt-6 pt-6">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">需要修改密码？点击右侧按钮进行修改</div>
          <BaseButton
            type="primary"
            :loading="loading"
            size="small"
            class="!px-4"
            @click="handleUpdatePassword"
          >
            <template #icon>
              <BaseIcon name="icon-lock" class="mr-1" />
            </template>
            修改密码
          </BaseButton>
        </div>
      </div>
    </div>
  </a-modal>

  <!-- 修改密码弹窗 -->
  <BaseForm
    v-model:visible="showPasswordModal"
    title="修改密码"
    :model-value="passwordForm"
    :rules="passwordRules"
    :loading="loading"
    :width="520"
    @submit="handlePasswordSubmit"
  >
    <template #form-items>
      <a-form-item label="当前密码" field="password">
        <a-input
          v-model="passwordForm.password"
          type="password"
          size="large"
          placeholder="请输入当前密码"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="新密码" field="newPassword">
        <a-input
          v-model="passwordForm.newPassword"
          type="password"
          size="large"
          placeholder="请输入新密码"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="确认新密码" field="confirmPassword">
        <a-input
          v-model="passwordForm.confirmPassword"
          type="password"
          size="large"
          placeholder="请再次输入新密码"
          allow-clear
        />
      </a-form-item>
    </template>
  </BaseForm>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores'
import { useNotification } from '@/composables/useNotification'
import { useLoading } from '@/composables/useLoading'
import BaseIcon from '@/components/BaseIcon.vue'
import { authService } from '@/services/auth'
import { systemUserService } from '@/services/systemUser'
import { LoginType } from '@/config'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import '@/assets/styles/components/header.css'
import BaseButton from '@/components/BaseButton.vue'
import BaseForm from '@/components/BaseForm.vue'

const router = useRouter()
const authStore = useAuthStore()
const notify = useNotification()
const { loading, loadingText, startLoading, stopLoading } = useLoading()

// 从store获取用户信息
const userInfo = computed(() => {
  if (!authStore.isLoggedIn || !authStore.userInfo) {
    return {
      name: '未登录',
      account: '',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=guest',
      role: '访客',
      realName: '',
      email: '',
      phone: '',
      birthday: '',
      sex: undefined as 1 | 2 | undefined,
      status: 1 as 1 | 2, // 默认正常状态
      roles: [] as string[],
      permissions: [] as string[],
    }
  }

  const info = authStore.userInfo
  return {
    ...info,
    avatar: info.avatar || 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + info.account,
    role: info.role || info.roles?.[0] || '普通用户',
    status: info.status || (info.normal ? 1 : 2), // 如果没有status字段，则用normal字段判断
    realName: info.realName || '',
    email: info.email || '',
    phone: info.phone || '',
    birthday: info.birthday || '',
    sex: info.sex,
  }
})

// 修改退出登录处理函数
const handleLogout = async () => {
  try {
    startLoading('退出中...')
    await authService.logout(LoginType.ADMIN)
    authStore.clearAuth()
    notify.success('已退出登录')
    router.push('/login')
  } catch {
    notify.error('退出登录失败，请重试')
  } finally {
    stopLoading()
  }
}

const userMenuVisible = ref(false)

const notifications = ref([
  {
    id: 1,
    title: '系统更新提醒',
    content: '系统将于今晚22:00进行例行维护',
    time: '10分钟前',
    type: 'info',
  },
  {
    id: 2,
    title: '待办事项',
    content: '您有3待处理的任务需要关注',
    time: '30分钟前',
    type: 'warning',
  },
])

const handleVisibleChange = (value: boolean) => {
  userMenuVisible.value = value
}

const showProfileModal = ref(false)
const showPasswordModal = ref(false)
const passwordForm = ref({
  password: '',
  newPassword: '',
  confirmPassword: '',
})

// 添加处理函数
const handleShowProfile = () => {
  showProfileModal.value = true
}

// 修改密码弹窗显示处理函数
const handleUpdatePassword = () => {
  showPasswordModal.value = true
}

// 修改密码表单验证规则
const passwordRules = {
  password: [
    { required: true, message: '请输入当前密码' },
    { minLength: 6, message: '密码长度不能小于6位' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { minLength: 6, message: '密码长度不能小于6位' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    { minLength: 6, message: '密码长度不能小于6位' },
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if (value !== passwordForm.value.newPassword) {
          callback('两次输入的密码不一致')
        }
        callback()
      },
    },
  ],
}

// 修改密码提交处理函数
const handlePasswordSubmit = async () => {
  try {
    startLoading('更新密码中...')

    // 构造API所需参数
    const params = {
      systemUserId: authStore.userInfo?.systemUserId as string,
      password: passwordForm.value.password,
      newPassword: passwordForm.value.newPassword,
    }
    // 更新密码
    await systemUserService.updatePassword(params)

    notify.success('密码更新成功')
    showPasswordModal.value = false

    // 重置表单
    passwordForm.value = {
      password: '',
      newPassword: '',
      confirmPassword: '',
    }
  } catch (error) {
    notify.error(error instanceof Error ? error.message : '密码更新失败')
  } finally {
    stopLoading()
  }
}
// 设置页面跳转处理函数
const handleSettings = () => {
  router.push('/settings/system-users')
}
</script>
